package com.mriassl.rabbitmq.unack;

import java.io.IOException;
import java.util.Scanner;

import com.mriassl.rabbitmq.base.AbstractProducer;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;

public class MessageProducer extends AbstractProducer {
	
	@Override
	protected void doSometing(Connection connt, Channel channelt) throws IOException {
	    
	    channel.exchangeDeclare(Consts.EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true, false, null);
        channel.queueDeclare(Consts.QUEUE_NAME, true, false, false, null);
        channel.queueBind(Consts.QUEUE_NAME, Consts.EXCHANGE_NAME, Consts.ROUTING_KEY);
        channel.confirmSelect();
        channel.basicQos(3);
		int count = 0;
		while(count<60){
			String message = "Hello World! " + count;
			channel.basicPublish(Consts.EXCHANGE_NAME, Consts.ROUTING_KEY, MessageProperties.PERSISTENT_BASIC, message.getBytes());
			System.out.println(" [x] Sent '" + message + "'");
			count++;
		}
		long start = System.currentTimeMillis();  
        channel.addConfirmListener(new ConfirmListener() {  
              
            @Override  
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {  
                System.out.println("nack: deliveryTag = "+deliveryTag+" multiple: "+multiple);  
            }  
              
            @Override  
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {  
                System.out.println("ack: deliveryTag = "+deliveryTag+" multiple: "+multiple);  
            }  
        });  
        System.out.println("执行waitForConfirmsOrDie耗费时间: "+(System.currentTimeMillis()-start)+"ms");
	}
	
	public static void main(String[] args) throws Exception {
		MessageProducer plog = new MessageProducer();
		plog.init();
		Scanner input = new Scanner(System.in);
        String val = null;
        do{
            plog.doSometing(null,null);
            val = input.next();
        }while(!val.equals("#"));
        input.close();
        plog.close();
	}
	
}